<?php
/**
 * Created by PhpStorm
 * User: @leisen
 * Date: 2022/7/18
 * Time: 5:08 PM
 */

namespace Frieza\Modules\Devidepackage\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DevidePackage\PackageNoteConf as mPackageNoteConf;
use Doraemon\model\DevidePackage\PackageRelatedUser as mPackageRelatedUser;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\service\Content\ContentRelatedLabel;
use Doraemon\service\DevidePackage\PackageRelatedUser as sPackageRelatedUser;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\service\DevidePackage\NoteLabelPackage as sNoteLabelPackage;
use Encore\Admin\Grid;
use Doraemon\model\DevidePackage\NoteLabelPackage as mNoteLabelPackage;
use Illuminate\Support\MessageBag;

class NoteLabelPackage extends Controller
{
    const MANAGE = 'manage';
    const HIGH = 'high';
    const NORMAL = 'normal';
    public $role = 'normal';
    const NORMAL_MENU = [
        1 => [
            'tab_id' => 1,
            'tab_name' => '领取任务',
        ],
        2 => [
            'tab_id' => 2,
            'tab_name' => '做任务',
            'status' => mPackageRelatedUser::STATUS_0,
            'column_method' => 'normalSub',
        ],
        3 => [
            'tab_id' => 3,
            'tab_name' => '待修改',
            'status' => mPackageRelatedUser::STATUS_2,
            'column_method' => 'normalUpd',
        ],
        4 => [
            'tab_id' => 4,
            'tab_name' => '待审核',
            'status' => [mPackageRelatedUser::STATUS_1,mPackageRelatedUser::STATUS_3],
            'column_method' => 'normalAudit',
        ],
        5 => [
            'tab_id' => 5,
            'tab_name' => '已完成',
            'status' => mPackageRelatedUser::STATUS_4,
            'column_method' => 'normalOver',
        ],
    ];
    const MANAGE_MENU = [
        6=>[
            'tab_id' => 6,
            'tab_name' => '未领取',
        ],
        7 => [
            'tab_id' => 7,
            'tab_name' => '待审核',
            'status' => [mPackageRelatedUser::STATUS_1, mPackageRelatedUser::STATUS_3],
            'column_method' => 'manageAudit',
        ],
        8 => [
            'tab_id' => 8,
            'tab_name' => '已审核待修改',
            'status' => mPackageRelatedUser::STATUS_2,
            'column_method' => 'manageAudit',
        ],
        9 => [
            'tab_id' => 9,
            'tab_name' => '已领取待提交',
            'status' => mPackageRelatedUser::STATUS_0,
            'column_method' => 'manageReceive',
        ],
        10 => [
            'tab_id' => 10,
            'tab_name' => '已完成',
            'status' => mPackageRelatedUser::STATUS_4,
            'column_method' => 'manageAudit',
        ],
        11 => [
            'tab_id' => 11,
            'tab_name' => '配置项',
        ],
        12 => [
            'tab_id' => 12,
            'tab_name' => '统计信息',
            'status' => mPackageRelatedUser::STATUS_4,
            'column_method' => 'manageStatistics',
        ],
    ];

    public function index(Request $request, Content $content, $tabId = 0)
    {
        $params = $request->all();
        $this->role = $this->checkRole();
        if (in_array($this->role, [self::HIGH, self::NORMAL]) && Admin::user()->cannot('package_note_label')) {
            return $content->header('您无权访问此页面')->withError('您无权访问此页面');
        }
        if ($this->role != self::MANAGE && $tabId > 5) {
            return redirect(url('/admin/devidepackage/pack-label/1'));
        }
        if (!isset($params['finish_time']) && $tabId == 12) {
            $params['finish_time'] = [
                'start' => date('Y-m-d H:i:s', strtotime('-30 days')),
                'end' => date('Y-m-d H:i:s'),
            ];
            $request->merge([
                'finish_time' => $params['finish_time'],
            ]);
        }

        $tab = $this->getTabs($tabId);
        return $content
            ->header('note打标签分包管理')
            ->breadcrumb(
                ['text' => 'note打标签分包管理',]
            )
            ->body($tab)->row(self::listAction($request, $tabId));
    }

    public function getTabs($tabId)
    {
        $tab = new Tab();
        $menu = $this->role == 'manage' ? self::MANAGE_MENU : self::NORMAL_MENU;
//        $menu = self::MANAGE_MENU;
//        $menu = self::NORMAL_MENU;
        foreach ($menu as $val) {
            $url = "/admin/devidepackage/pack-label/{$val['tab_id']}";
            $tab->addLink($val['tab_name'], $url, $tabId == $val['tab_id']);
        }
        return $tab;
    }

    //校验用户角色
    public function checkRole(): string
    {
//        return 'manage';
        $package_manager = Admin::user()->isRole('package_manager');
        $package_high_operate = Admin::user()->isRole('package_high_operate');
        //$package_normal_operate = Admin::user()->isRole('package_normal_operate');
        if ($package_manager) {
            return self::MANAGE;
        }
        if ($package_high_operate) {
            return self::HIGH;
        }

        return self::NORMAL;
    }

    public function listAction($request = [], $tabId)
    {
        $list = [];
        switch ($tabId) {
            case 1://领取任务
            case 6://未领取
                $listGrid = $this->noteLabelPackage($request, $tabId);
                $list = $listGrid->render();
                break;
            case 2://做任务
            case 3://待修改
            case 4://待审核
            case 5://待审核
            case 7://待审核
            case 8://待审核
            case 9://已经取待提交
            case 10://待审核
            case 12://统计信息
                //统计信息
                $listGrid = $this->packageRelatedUser($request, $tabId);
                $list = $listGrid->render();
                break;
            case 11:
                //统计信息
                $listGrid = $this->collocationList();
                $list = $listGrid->render();
                break;
        }
        return $list;
    }

    public function packageRelatedUser($request, $tabId)
    {
        $page = $request['page'] ?? 1;
        $pageSize = $request['per_page'] ?? 20;
        $limit = [($page - 1) * $pageSize, $pageSize];
        //查询待领取的信息
        if ($this->role == self::MANAGE) {
            $status = self::MANAGE_MENU[$tabId]['status'];
            $way = self::MANAGE_MENU[$tabId]['column_method'];
        } else {
            $status = self::NORMAL_MENU[$tabId]['status'];
            $where['staff_id'] = Admin::user()->id;
            $way = self::NORMAL_MENU[$tabId]['column_method'];
        }
        $where['status'] = $status;
        $finishTime = $request['finish_time'] ?? [];
        if (!empty($finishTime['start']) && !empty($finishTime['end'])) {
            $where['AND']['finish_time[<>]'] = [$finishTime['start'], $finishTime['end']];
        }
        if (!empty($request['staff_id'])) {
            $where['staff_id'] = $request['staff_id'];
        }

        $data = sPackageRelatedUser::getListByWhere($where, $limit);
        $gridModel = new pGridDataModel($data['list'], $data['num']);
        $userModel = config('admin.database.users_model');
        return Admin::grid($gridModel, function (Grid $grid) use ($tabId, $way, $userModel, $where) {
            $grid->disableExport();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            if ($tabId == 12) {
                $grid->tools(function (Grid\Tools $tools) use ($where) {
                    $href = '/admin/devidepackage/note-labels/down-excel?condition=' . base64_encode(json_encode($where));
                    $tools->append("<a href={$href} class='btn button-success'><i class='fa fa-file-excel-o'></i>>导出</a>");
                });
            }
            if ($tabId == 12) {
                $grid->disableActions();
            } else {
                $grid->disableFilter();
            }
            $grid->filter(function (Grid\Filter $filter) use ($userModel) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 2, function ($filter) {
                    $filter->between('finish_time', '任务完成时间')->datetime();
                });
                $filter->column(1 / 2, function ($filter) use ($userModel) {
                    $filter->equal('staff_id', '领取人信息')->select($userModel::all()->pluck('name', 'id'));
                });
            });
            $grid->column('id', '领取关联ID');
            $grid->column('pack_id', '任务包ID');

            self::$way($grid,$tabId);

            $grid->actions(function (Grid\Displayers\Actions $actions) use ($tabId) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();
                if (in_array($tabId, [2, 3])) {
                    $operation = $tabId == 2 ? '做任务' : '去修改';
                    $actions->prepend('<a class="fa reload-data fa-hand-peace-o submit-package" href="javascript:;" data-id="' . $actions->row->id . '">提交任务</a>');
                    $actions->prepend('<a target="_blank" class="fa reload-data fa-hand-paper-o continue-package" href="/admin/devidepackage/note-label/' . $actions->row->pack_id . '?tab_id='.$tabId.'" >' . $operation . '</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                }
                if ($tabId == 7) {
                    $actions->prepend('<p><a class="fa reload-data fa-check finish-package" href="javascript:;" data-id="' . $actions->row->id . '">标记完成</a>&nbsp;&nbsp;&nbsp;&nbsp;</p>');
                    if($actions->row->sub_type == 1){
                        $actions->prepend('<p><a class="fa reload-data fa-times reedit-package" href="javascript:;" data-id="' . $actions->row->id . '" >打回修改</a></p>');
                    }
                    $actions->prepend('<p><a target="_blank" class="fa reload-data fa-hand-paper-o continue-package" href="/admin/devidepackage/note-label/' . $actions->row->pack_id . '?tab_id='.$tabId.'" >审核详情</a>');
                }
                if ($tabId == 9) {
                    $actions->prepend('<p><a target="_blank" class="fa reload-data fa-hand-paper-o continue-package" href="/admin/devidepackage/note-label/' . $actions->row->pack_id . '?tab_id='.$tabId.'" >查看任务详情</a>');
                }
            });
            Admin::script($this->submitPopup());
            Admin::script($this->reEditPopup());
            Admin::script($this->finishPopup());
        });
    }

    //兼职-做任务
    public static function normalSub($grid,$tabId)
    {
        $grid->column('add_time', '领取任务时间');
        $grid->column('expire_time', '任务包到期时间')->display(function () {
            return $this->expire_time;
        });
        $grid->column('note_num', 'note数');
        $grid->column('has_tag_note_num', '被打标签note数');
        $grid->column('has_tag_num', '打标签总数');
    }

    //兼职-已完成
    public static function normalOver($grid,$tabId)
    {
        $grid->column('add_time', '领取任务时间');
        $grid->column('finish_time', '任务完成时间');
        $grid->column('sub_type', '提交类型')->display(function () {
            return mPackageRelatedUser::SUB_TYPE_MAP[$this->sub_type];
        });
        $grid->column('note_num', 'note数');
        $grid->column('has_tag_note_num', '被打标签note数');
        $grid->column('has_tag_num', '打标签总数');
        $grid->column('problem_note_num', '问题note数');
        $grid->column('adm_remark', '整包备注')->limit(30);
        return $grid;
    }

    //兼职-待审核
    public static function normalAudit($grid,$tabId)
    {
        $grid->column('status', '任务状态')->display(function () {
            return mPackageRelatedUser::STATUS_MAP[$this->status];
        });
        $grid->column('add_time', '领取任务时间');
        $grid->column('sub_time', '任务提交时间');
        $grid->column('sub_type', '提交类型')->display(function () {
            return mPackageRelatedUser::SUB_TYPE_MAP[$this->sub_type];
        });
        $grid->column('note_num', 'note数');
        $grid->column('has_tag_note_num', '被打标签note数');
        $grid->column('has_tag_num', '打标签总数');
        $grid->column('problem_note_num', '问题note数');
        $grid->column('adm_remark', '整包备注')->limit(30);
        return $grid;
    }

    //兼职-待修改
    public static function normalUpd($grid,$tabId)
    {
        $grid->column('status', '任务状态')->display(function () {
            return mPackageRelatedUser::STATUS_MAP[$this->status];
        });
        $grid->column('add_time', '领取任务时间');
        $grid->column('note_num', 'note数');
        $grid->column('has_tag_note_num', '被打标签note数');
        $grid->column('has_tag_num', '打标签总数');
        $grid->column('problem_note_num', '问题note数');
        $grid->column('adm_remark', '整包备注')->limit(30);
        return $grid;
    }

    //管理员-待审核
    public static function manageAudit($grid,$tabId)
    {
        $grid->column('status', '任务状态')->display(function () {
            return mPackageRelatedUser::STATUS_MAP[$this->status];
        });
        $grid->column('add_time', '领取任务时间');
        if($tabId == 10){
            $grid->column('finish_time', '任务完成时间');
        }else{
            $grid->column('sub_time', '任务提交时间');
        }
        $grid->column('sub_type', '提交类型')->display(function () {
            return mPackageRelatedUser::SUB_TYPE_MAP[$this->sub_type];
        });
        $grid->column('note_num', 'note数');
        $grid->column('has_tag_note_num', '被打标签note数');
        $grid->column('has_tag_num', '打标签总数');
        $grid->column('problem_note_num', '问题note数');
        $admRemark = $grid->column('adm_remark', '整包备注')->width(110);
        if ($tabId != 10) {
            $admRemark->editable('textarea');
        }

        $grid->column('staff_id', '认领人')->display(function () {
            return 'id:' . $this->staff_id . '<br/>用户名：' . Admin::user()->find($this->staff_id)->name;
        });
        return $grid;
    }

    //管理员-统计信息
    public static function manageStatistics($grid,$tabId)
    {
        $grid->column('staff_id', '认领人')->display(function () {
            return 'id:' . $this->staff_id . '<br/>用户名：' . Admin::user()->find($this->staff_id)->name;
        });
        $grid->column('add_time', '领取任务时间');
        $grid->column('finish_time', '任务完成时间');
        $grid->column('note_num', '包含note数');
        $grid->column('has_tag_note_num', '被打标签note数');
        $grid->column('has_tag_num', '打标签总数');
        $grid->column('problem_note_num', '问题note数');
        $grid->column('adm_remark', '整包备注')->limit(30);
        $grid->column('admin_id', '审核人')->display(function () {
            return 'id:' . $this->admin_id . '<br/>用户名：' . Admin::user()->find($this->admin_id)->name;
        });
        return $grid;
    }

    public static function manageReceive($grid,$tabId)
    {
        $grid->column('add_time', '领取任务时间');
        $grid->column('expire_time', '任务到期时间')->display(function () {
            $str = $this->expire_time . '<br/>';
            if (date('Y-m-d H:i:s') >= $this->expire_time) {
                $span = ' 已到期，系统将自动提交';
            } else {
                $diff = strtotime($this->expire_time) - time();
                if ($diff > 3600) {
                    $hours = intval($diff / 3600);
                    $time = $hours . "时";
                } else {
                    $time = gmstrftime('%M分钟', $diff);
                }
                $span = '距离到期还有' . $time;
            }
            $str .= '<span style="color: red">' . $span . '</span>';
            return $str;
        });
        $grid->column('note_num', 'note数');
        $grid->column('staff_id', '认领人')->display(function () {
            return 'id:' . Admin::user()->id . '<br/>用户名：' . Admin::user()->find($this->staff_id)->name;
        });
    }

    public function noteLabelPackage($request, $tab_id)
    {
        $pageSize = 10;
        $limit = [0, $pageSize];
        //查询待领取的信息
        if ($this->role == self::MANAGE) {
            $page = $request['page'] ?? 1;
            $pageSize = $request['per_page'] ?? 20;
            $limit = [($page - 1) * $pageSize, $pageSize];
        } else if ($this->role == self::NORMAL) {
            $where['show_time[<]'] = date('Y-m-d H:i:s');
        }
        $where['status'] = mNoteLabelPackage::STATUS_1;
        $data = sNoteLabelPackage::getListByWhere($where, $limit);
        $gridModel = new pGridDataModel($data['list'], $data['num'], ['perPage' => $pageSize,]);
        return Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            if ($this->role != self::MANAGE) {
                $grid->disablePagination();
            }
            $grid->column('id', '任务包ID');
            $grid->column('add_time', '打包时间');
            $grid->column('validity', '任务包有效期')->display(function () {
                return $this->validity . "小时";
            });
            $grid->column('note_num', 'note数');
            if (in_array($this->role, ['high', 'normal'])) {
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->prepend('<a class="fa reload-data fa-get-pocket received-package" data-id="' . $actions->row->id . '" href="javascript:;" >领取任务</a><br>');
                });
            } else {
                $grid->column('show_time', '普通操作员开始展示时间');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->disableView();
                });
            }
            Admin::script($this->receivedPopup());
        });
    }

    //配置项
    public function collocationList()
    {
        $list = mPackageNoteConf::getInfo();
        $data = [
            [
                'note_num' => $list['note_num'],
                'quality' => $list['quality'],
                'advance_hour' => $list['advance_hour'],
                'validity' => $list['validity'],
            ]
        ];
        $gridModel = new pGridDataModel($data, count($data), []);
        return Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->expandFilter();
            $grid->disableActions();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->column('note_num', '任务包中note数')->editable()->help('请输入100-300的正整数哦');
            $grid->column('quality', '任务包中质量')->editable()->help('优质质量请输入1，普通请输入2，全部请输入3，普通+优质输入4');
            $grid->column('advance_hour', '优质兼职提前多少小时可见任务包')->editable()->help('请输入10以下的正整数哦');
            $grid->column('validity', '任务包有效期')->editable()->help('正整数，单位为小时，从领取任务开始计算时间');
        });
    }

    //配置项
    public function collocation(Request $request)
    {
        $request = $request->all();
        if ($request['name'] == 'note_num' && ($request['value'] < 100 || $request['value'] > 300)) {
            return response()->json(['errors' => ['请输入100-300的正整数哦']], 422);
        }
        if ($request['name'] == 'advance_hour' && $request['value'] > 10) {
            return response()->json(['errors' => ['请输入10以下的正整数哦']], 422);
        }
        $data[$request['name']] = $request['value'];
        $data['admin_id'] = Admin::user()->id;
        $updNum = mPackageNoteConf::upd($data);
        $status = 1;
        $message = '修改成功';
        if (empty($updNum)) {
            return response()->json(['errors' => ['修改失败']], 422);
        }
        return response()->json([
            'status' => $status,
            'message' => $message
        ]);
    }

    //管理员添加整包备注
    public function addRemark(Request $request, $id)
    {
        $data['adm_remark'] = $request->input('value');

        $res = mPackageRelatedUser::upd($data, $id);
        if ($res) {
            return response()->json([
                'status' => 1,
                'message' => '添加成功'
            ]);
        }
        return response()->json([
            'status' => 0,
            'message' => '添加失败'
        ]);
    }

    //领取任务
    public function receivedpackage(Request $request)
    {
        $request = $request->all();
        $packageId = $request['id'];//任务包id
        $staffId = Admin::user()->id;
        //当有未修改的包时，领取不了
        $where['staff_id'] = Admin::user()->id;
        $where['status'] = mPackageRelatedUser::STATUS_2;
        $isUpd = mPackageRelatedUser::count($where);
        if (!empty($isUpd)) {
            return [
                'code' => 0,
                'msg' => '领取失败，请先操作待修改的任务包'
            ];
        }
        //查询包信息
        $packInfo = sNoteLabelPackage::getReceiveInfoById($packageId);
        if (empty($packInfo)) {
            return [
                'code' => 0,
                'msg' => '该包已被领取，请领取其他包'
            ];
        }
        $packInfo = sNoteLabelPackage::receive($packInfo, $staffId);
        if (!$packInfo) {
            return [
                'code' => 0,
                'msg' => '领取失败，请重试'
            ];
        }
        return [
            'code' => 1,
            'msg' => '领取成功'
        ];
    }

    public function receivedPopup()
    {
        return <<<SCRIPT
            $('.received-package').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认领取这个任务嘛？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认领取",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.post('/admin/devidepackage/receive-note-package', {'id':id}, function (data) {
                        $.pjax.reload('#pjax-container');
                        if(data.code == 1) {
                            swal(data.msg, '', 'success');
                        } else {
                            swal(data.msg, '', 'error');
                        }
                    });
                   
                }
            });
        });
SCRIPT;
    }

    //提交任务弹窗
    public function submitPopup()
    {
        return <<<SCRIPT
            $('.submit-package').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认要将这个任务提交审核吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认提交",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.post('/admin/devidepackage/submit-note-package', {'id':id}, function (data) {
                        $.pjax.reload('#pjax-container');
                        if(data.code == 1) {
                            swal(data.msg, '', 'success');
                        } else {
                            swal(data.msg, '', 'error');
                        }
                    });
                   
                }
            });
        });
SCRIPT;
    }

    //提交任务
    public function submitPackage(Request $request)
    {
        $request = $request->all();
        $id = $request['id'];
        //先查询包
        $info = sPackageRelatedUser::getInfo($id);
        if (empty($info)) {
            return [
                'code' => 0,
                'msg' => '该包不存在'
            ];
        }
        if (($info['staff_id'] != Admin::user()->id) ||
            (!in_array($info['status'], [mPackageRelatedUser::STATUS_0, mPackageRelatedUser::STATUS_2]))) {
            return [
                'code' => 0,
                'msg' => '该包不能被提交'
            ];
        }
        $status = $info['status'] == mPackageRelatedUser::STATUS_0 ? mPackageRelatedUser::STATUS_1 : mPackageRelatedUser::STATUS_3;
        //提交审核
        $res = sPackageRelatedUser::changePackageSubmit($id, $status);
        if ($res) {
            return [
                'code' => 1,
                'msg' => '提交成功'
            ];
        } else {
            return [
                'code' => 0,
                'msg' => '提交失败，请重试'
            ];
        }
    }

    //打回修改弹窗
    public function reEditPopup()
    {
        return <<<SCRIPT
            $('.reedit-package').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认要将这个任务打回修改吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认打回",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.post('/admin/devidepackage/note-label/reeditpackage', {'id':id}, function (data) {
                        $.pjax.reload('#pjax-container');
                        if(data.code == 1) {
                            swal(data.msg, '', 'success');
                        } else {
                            swal(data.msg, '', 'error');
                        }
                    });
                   
                }
            });
        });
SCRIPT;
    }

    //任务包打回修改
    public function reEditPackage(Request $request)
    {
        $request = $request->all();
        $id = $request['id'];
        $data['status'] = mPackageRelatedUser::STATUS_2;
        $data['admin_id'] = Admin::user()->id;
        $rs = mPackageRelatedUser::upd($data, $id);
        if ($rs) {
            return [
                'code' => 1,
                'msg' => '任务包打回成功'
            ];
        }
        return [
            'code' => 0,
            'msg' => '任务包打回失败'
        ];
    }

    //标记完成弹窗
    public function finishPopup()
    {
        return <<<SCRIPT
           
            $('.finish-package').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认要将这个任务标记完成吗？此操作不可逆哦",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认已完成",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.post('/admin/devidepackage/note-label/finishPackage', {'id':id}, function (data) {
                        $.pjax.reload('#pjax-container');
                        if(data.code == 1) {
                            swal(data.msg, '', 'success');
                        } else {
                            swal(data.msg, '', 'error');
                        }
                    });
                   
                }
            });
        });
SCRIPT;
    }

    //任务包标记完成
    public function finishPackage(Request $request)
    {
        $request = $request->all();
        $id = $request['id'];
        $data['status'] = mPackageRelatedUser::STATUS_4;
        $data['admin_id'] = Admin::user()->id;
        $data['finish_time'] = date('Y-m-d H:i:s');
        $rs = mPackageRelatedUser::upd($data, $id);
        if ($rs) {
            return [
                'code' => 1,
                'msg' => '任务包已标记完成'
            ];
        }
        return [
            'code' => 0,
            'msg' => '任务包标记完成失败'
        ];
    }

    public function downExcel(Request $request)
    {
        $params = $request->all();
        $where = $params['condition'];
        $where = json_decode(base64_decode($where), 1);
        $finishTime = $where['AND']['finish_time[<>]'];
        $diff = strtotime($finishTime[1]) - strtotime($finishTime[0]);
        if ($diff > 31 * 86400) {
            $error = new MessageBag(['title' => '导出失败，最大支持导出一个月数据']);
            return back()->with(compact('error'))->withInput();
        }
        $data = sPackageRelatedUser::getListByWhere($where);
        if (empty($data['num'])) {
            $error = new MessageBag(['title' => '导出失败，该期间暂无数据']);
            return back()->with(compact('error'))->withInput();
        }
        $list = [];
        foreach ($data['list'] as $val) {
            $list[] = [
                $val['id'],
                $val['pack_id'],
                'id:' . $val['staff_id'] . ' 用户名:' . Admin::user()->find($val['staff_id'])->name,
                $val['add_time'],
                $val['finish_time'],
                $val['note_num'],
                $val['has_tag_note_num'],
                $val['has_tag_num'],
                $val['problem_note_num'],
                $val['adm_remark'],
                'id:' . $val['admin_id'] . ' 用户名:' . Admin::user()->find($val['admin_id'])->name,
            ];
        }

        $downExcel = new DownExcel();
        $letter = range('A', 'K');
        $widths = ['A' => 10, 'B' => 10, 'C' => 20, 'D' => 25, 'E' => 25, 'F' => 10, 'G' => 10, 'H' => 10, 'I' => 10, 'J' => 15, 'k' => 20];
        $title = '统计信息导出';
        $downExcel->setFrontBold('1');
        $downExcel->setWidth($widths);
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);

        $header = [
            '领取关联ID', '任务包ID', '认领人', '任务领取时间', '任务完成时间', '包含note数',
            '被打标签的note数', '打标签总数', '问题note数', '整包备注', '审核人'
        ];

        foreach ($header as $key => $value) {
            //设置字体
            $downExcel->setFrontName($letter[$key]);
            //设置大小
            $downExcel->setFrontSize($letter[$key]);
        }

        $downExcel->create($list, $header);
        return back();
    }
}